package middleware

import (
	"encoding/json"
	"fmt"
	"github.com/didip/tollbooth"
	"github.com/didip/tollbooth/limiter"
	"github.com/gin-gonic/gin"
	"time"
)

func LimitHandler() gin.HandlerFunc {
	lmt := tollbooth.NewLimiter(1, &limiter.ExpirableOptions{
		DefaultExpirationTTL: 1 * time.Second,
	})
	data := map[string]interface{}{
		"code":    -1,
		"data":    nil,
		"message": "您访问过于频繁，系统安全检查认为恶意攻击。",
	}

	// 将map转换为JSON
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Error converting to JSON:", err)

	}

	lmt.SetMessage(string(jsonData))
	return func(c *gin.Context) {
		httpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)
		if httpError != nil {
			//c.JSON(http.StatusOK, gin.H{
			//	"code":    1,
			//	"message": "您的操作太频繁，请稍后再试！",
			//	"result":  nil,
			//})
			c.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))
			c.Abort()
		} else {
			c.Next()
		}
	}
}
